﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace Prism.Core.Storage
{
    public sealed class NonGroupStorageManager : StorageManager, IDataSaver
    {
        public NonGroupStorageManager()
            : base()
        {
            this.defGroupName = "data";
        }

        public NonGroupStorageManager(string profilePath, string defGroupName)
            : base(profilePath)
        {
            this.defGroupName = defGroupName;
        }

        string defGroupName;

        public void AddData(string accessName, Stream stream)
        {
            this.AddData(accessName, stream, this.DataTable.LastedVersion);
        }

        public void AddData(string accessName, Stream stream, Version version)
        {
            // 如果总表为空，则新建一个差分表送入总表，写入第一个文件，并计入长度。
            if (this.DataTable.IsEmpty)
            {
                var dataList = new DifferentialDataList();
                dataList.Version = new Version();
                this.DataTable.Add(dataList);
                dataList.Version.Value = 0f;
                this.DataTable.LastedVersion.Value = 0f;
                dataList.AddData(accessName, this.defGroupName, stream, this.DataTable);

            }
            // 如果总表不为空。
            else
            {
                var q = from i in this.DataTable
                        where i.Version == version
                        select i;
                var count = q.Count();
                // 如果找到了对应的版本，则送入数据。
                if (count == 1)
                {
                    var target = q.Single();
                    // 写入磁盘
                    target.AddData(accessName, this.defGroupName, stream, this.DataTable);

                }
                // 如果找不到对应的版本，则新建一个差分数据表。
                else if (count == 0)
                {
                    var dataList = new DifferentialDataList();
                    dataList.Version = version;
                    this.DataTable.Add(dataList);
                    // 写入磁盘
                    dataList.AddData(accessName, this.defGroupName, stream, this.DataTable);
                }
            }

            // 更新配置文件。
            this.UpdateProfileToDisk();
        }
    }
}
